/**
 * 
 */
package com.scpii.universal.service.mobile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.scpii.universal.hibernate.entity.EnterpShopTab;
import com.scpii.universal.hibernate.entity.UserWeiboTab;
import com.scpii.universal.pb.PbUniversal.PBRESULT;
import com.scpii.universal.pb.PbUniversal.PbEnterpShopListCS;
import com.scpii.universal.pb.PbUniversal.PbEnterpShopListSC;
import com.scpii.universal.pb.PbUniversal.PbEnterpWeiboCS;
import com.scpii.universal.pb.PbUniversal.PbEnterpWeiboSC;
import com.scpii.universal.pb.PbUniversal.PbShopFilterOptionCS;
import com.scpii.universal.pb.PbUniversal.PbShopFilterOptionSC;
import com.scpii.universal.pb.PbUniversalBasic.PbEnterpShop;
import com.scpii.universal.pb.PbUniversalBasic.PbEnterpShopList;
import com.scpii.universal.pb.PbUniversalBasic.PbEnterpWeibo;
import com.scpii.universal.pns.hibernate.entity.TagValues;
import com.scpii.universal.pns.hibernate.entity.Tags;
import com.scpii.universal.pns.service.TagValuesService;
import com.scpii.universal.pns.service.TagsService;
import com.scpii.universal.service.EnterpShopTabService;
import com.scpii.universal.service.UserWeiboTabService;
import com.scpii.universal.util.Const;
import com.scpii.universal.util.CoordinateUtil;

/**
 * UniversalApi
 * 
 * @author 甘建新 2012-7-11下午11:03:15
 */
public class MobileEnterpService {
//	private EnterpShopTabService enterpShopTabService = new EnterpShopTabService();
//	private UserWeiboTabService userWeiboTabService = new UserWeiboTabService();
	
	private EnterpShopTabService enterpShopTabService;
	private UserWeiboTabService userWeiboTabService;
	private TagValuesService tagValuesService;
	private TagsService tagsService;
	
	private Logger log = Logger.getLogger(MobileEnterpService.class);
	private String LOG_METHOD_NAME="";
	/**
	 * 获得企业门店信息 GET_ENTERP_SHOPLIST
	 * 
	 * @param enterpShopListCS
	 * @return
	 * @author 甘建新 2012-7-11下午11:52:27
	 */
	public byte[] getEnterpShopList(byte[] bytes) {
		LOG_METHOD_NAME="getEnterpShopList";
		
		PbEnterpShopListSC.Builder pbEnterpShopListSCB = PbEnterpShopListSC.newBuilder();
		PbEnterpShopList.Builder pbEnterpShopList = PbEnterpShopList.newBuilder();
		if (bytes != null) {
			try {
				PbEnterpShopListCS pbEnterpShopListCS = PbEnterpShopListCS.parseFrom(bytes);
				int appId = pbEnterpShopListCS.getIntAppId();
				int contentId = pbEnterpShopListCS.getIntContentId();
				String varLongitude = pbEnterpShopListCS.getVarLongitude();//经度
				String varLatitude = pbEnterpShopListCS.getVarLatitude();//纬度
				String varRadius = pbEnterpShopListCS.getVarRadius();//半径
				String varKeyWord = pbEnterpShopListCS.getVarKeyWord();
				String varRegion = pbEnterpShopListCS.getVarRegion();
				String varTag = pbEnterpShopListCS.getVarTag();
				int cateId = pbEnterpShopListCS.getCateId();
				
				log.info(LOG_METHOD_NAME+"【appId:"+appId+",contentId:"+contentId+",cateId:"+cateId+",varLatitude:"+varLatitude+
						",varLongitude:"+varLongitude+",varRadius:"+varRadius+",varKeyWord:"+varKeyWord+",varRegion:"+varRegion+",varTag:"+varTag+"】");
				
				//查询数据
				StringBuffer sql = new StringBuffer();
				Map<String,Object> argsMap = new HashMap<String,Object>();
				populateSearchSql(sql, argsMap, varKeyWord, varRegion, contentId,appId,cateId);
				List<EnterpShopTab> enterpShopList = enterpShopTabService.getShopByPageNo(0, 0, sql.toString(), argsMap);
				String targetIds = "";
				if (!StringUtils.isBlank(varTag)) {
					StringBuffer sb = new StringBuffer("");
					//获取标签关联的所有target
					List<TagValues> targets = tagValuesService.getTargetsByTagId(varTag);
					for (TagValues tagValues : targets) {
						sb.append(tagValues.getTargetId()+",");
					}
					targetIds = sb.toString();
				}
				List<EnterpShopTab> restults = new ArrayList<EnterpShopTab>();
				if (enterpShopList!=null && enterpShopList.size()>0) {
					if(checkNum(varLongitude) && checkNum(varLatitude)) {
						//经纬度参数不为空计算距离并排序
						double[] pointA = CoordinateUtil.lonLat2Mercator(Double.valueOf(varLongitude), Double.valueOf(varLatitude));
						boolean isFilterRadius = checkNum(varRadius);//是否过滤半径
						for (EnterpShopTab enterpShopTab : enterpShopList) {
							//剔除经度或纬度为空的
							if(checkNum(enterpShopTab.getVarShopLongitude()) && checkNum(enterpShopTab.getVarShopLatitude())){
								double[] pointB = CoordinateUtil.lonLat2Mercator(Double.valueOf(enterpShopTab.getVarShopLongitude()), Double.valueOf(enterpShopTab.getVarShopLatitude()));
								double distance = CoordinateUtil.calc2PointDistance(pointA, pointB);
								enterpShopTab.setDistance(distance);
								if(isFilterRadius){
									if (Double.valueOf(varRadius) >= distance) {
										restults.add(enterpShopTab);
									}
								} else {
									restults.add(enterpShopTab);
								}
							}
						}
						Collections.sort(restults, new EnterpShopTab());
					} else {
						for (EnterpShopTab enterpShopTab : enterpShopList) {
							if(checkNum(enterpShopTab.getVarShopLongitude()) && checkNum(enterpShopTab.getVarShopLatitude())){
								restults.add(enterpShopTab);
							}
						}
					}
					boolean isFilterTag = checkNum(varTag);
					if (isFilterTag) {
						//根据标签过滤
						for (EnterpShopTab shop : restults) {
							long targetId = cateId>0?(Const.CATE_ID_PRE + shop.getIntShopId()):(Const.SHOP_ID_PRE + shop.getIntShopId());
							if (targetIds.contains(String.valueOf(targetId))) {
								pbEnterpShopList.addPbEnterpShopList(populateShopBuilder(shop));
							}
						}
					}else {
						for (EnterpShopTab shop : restults) {
							pbEnterpShopList.addPbEnterpShopList(populateShopBuilder(shop));
						}
					}
					if(pbEnterpShopList.getPbEnterpShopListList().size() > 0){
						pbEnterpShopListSCB.setPbEnterpShopList(pbEnterpShopList);
						pbEnterpShopListSCB.setExeResult(PBRESULT.SUCCESS);
						log.info(LOG_METHOD_NAME+Const.LOG_DATA_SUCCESS);
					} else {
						log.info(LOG_METHOD_NAME+Const.LOG_DATA_NULL);
						pbEnterpShopListSCB.setExeResult(PBRESULT.NULL);
					}
				}else {
					log.info(LOG_METHOD_NAME+Const.LOG_DATA_NULL);
					pbEnterpShopListSCB.setExeResult(PBRESULT.NULL);
				}
			} catch (Exception e) {
				log.error(LOG_METHOD_NAME+Const.LOG_DATA_EXCEPTION,e);
				e.printStackTrace();
				pbEnterpShopListSCB.setExeResult(PBRESULT.EXCEPTION);
			}
		} else {
			log.info(LOG_METHOD_NAME+Const.LOG_BYTE_NULL);
			pbEnterpShopListSCB.setExeResult(PBRESULT.FAILED);
		}
		return pbEnterpShopListSCB.build().toByteArray();
	}

	private PbEnterpShop.Builder populateShopBuilder(EnterpShopTab shop) {
		PbEnterpShop.Builder pbShopB = PbEnterpShop.newBuilder();
		pbShopB.setIntAppId(shop.getIntAppId());
		pbShopB.setIntEnterpId(shop.getIntEnterpId());
		pbShopB.setIntShopId(shop.getIntShopId());
		
		pbShopB.setVarShopAddress(shop.getVarShopAddress());
		pbShopB.setVarShopCity(shop.getVarShopCity());
		pbShopB.setVarShopCountry(shop.getVarShopCountry());
		pbShopB.setVarShopLatitude(shop.getVarShopLatitude());
		pbShopB.setVarShopLongitude(shop.getVarShopLongitude());
		pbShopB.setVarShopName(shop.getVarShopName());
		pbShopB.setVarShopPhoneNum(shop.getVarShopPhonenum());
		pbShopB.setVarShopPostNum(shop.getVarShopPostnum());
		pbShopB.setVarShopProvince(shop.getVarShopProvince());
		pbShopB.setVarOpenTime(shop.getVarOpenTime()==null?"":shop.getVarOpenTime());
		pbShopB.setVarBusinessArea(shop.getVarBusinessArea()==null?"":shop.getVarBusinessArea());
		pbShopB.setVarDesc(shop.getVarDesc()==null?"":shop.getVarDesc());
		pbShopB.setVarIconUrl(shop.getVarIconUrl()==null?"":shop.getVarIconUrl());
		pbShopB.setVarThumbImg(shop.getVarThumbImg()==null?"":shop.getVarThumbImg());
		pbShopB.setVarDistance((shop.getDistance()==null||"NaN".equals(shop.getDistance().toString()))?"无法计算":CoordinateUtil.formatDistance(shop.getDistance()));
		return pbShopB;
	}
	
	private void populateSearchSql(StringBuffer sql,
			Map<String, Object> argsMap, String varKeyWord, String varRegion,
			int intContentId,int appId,int cateId) {
		sql.append("select * from ENTERP_SHOP_TAB e WHERE e.INT_DELETE_SIGN=0");
		if (intContentId != 0) {
			sql.append(" AND e.INT_CONTENT_ID=:contentId");
			argsMap.put("contentId", intContentId);
		}
		if (!StringUtils.isBlank(varKeyWord)) {
			sql.append(" AND concat(VAR_SHOP_NAME,VAR_DESC) like '%"+varKeyWord+"%'");
		}
		if (!StringUtils.isBlank(varRegion)) {
			String[] regions = varRegion.split("#");
			if (!"-1".equals(regions[0].trim())) {
				sql.append(" AND VAR_SHOP_PROVINCE like '%"+regions[0]+"%'");
			}
			if (!"-1".equals(regions[1].trim())) {
				sql.append(" AND VAR_SHOP_CITY like '%"+regions[1]+"%'");
			}
			if (regions.length >= 3 && !"-1".equals(regions[2].trim())) {
				sql.append(" AND VAR_SHOP_AREA like '%"+regions[2]+"%'");
			}
		}
		sql.append(" AND e.INT_APP_ID=:appId");
		argsMap.put("appId", appId);
		if( cateId > 0) {
			sql.append(" AND e.INT_CATE_ID=:cateId");
			argsMap.put("cateId", cateId);
		} else {
			sql.append(" AND e.INT_CATE_ID=0");
		}
	}
	
	public byte[] getShopFilterOptions(byte[] bytes) {
		LOG_METHOD_NAME="getShopFilterOptions";
		PbShopFilterOptionSC.Builder pbShopFilterOptionSCB = PbShopFilterOptionSC.newBuilder();
		try {
			PbShopFilterOptionCS pbShopFilterOptionCS = PbShopFilterOptionCS.parseFrom(bytes);
			int appId = pbShopFilterOptionCS.getIntAppId();
			int cateId = pbShopFilterOptionCS.getCateId();
			log.info(LOG_METHOD_NAME+"【appId:"+appId+"】");
			long objectId;
			if(cateId > 0){
				objectId = Const.CATE_ID_PRE + cateId;
			} else {
				objectId = Const.SHOP_ID_PRE + appId;
			}
			List<Tags> results = tagsService.getTagsByAppId(objectId);
			JSONArray datas = new JSONArray();
			JSONObject data = null;
			for (Tags tags : results) {
				data = new JSONObject();
				data.put("id", tags.getId());
				data.put("name", tags.getTitle());
				datas.add(data.toString());
			}
			String filter = "{\"tags\":"+datas+"}";
			pbShopFilterOptionSCB.setVarDatas(filter);
			pbShopFilterOptionSCB.setExeResult(PBRESULT.SUCCESS);
			log.info(LOG_METHOD_NAME+Const.LOG_DATA_SUCCESS);
		} catch (Exception e) {
			log.error(LOG_METHOD_NAME+Const.LOG_DATA_EXCEPTION,e);
			e.printStackTrace();
			pbShopFilterOptionSCB.setExeResult(PBRESULT.EXCEPTION);
		}
		return pbShopFilterOptionSCB.build().toByteArray();
	}
	
	/**
	 * 检测是否为空，是否全是数字除.
	 * @author Taylor
	 * 2012-10-3 上午09:45:01
	 * @param pNum
	 * @return
	 * boolean
	 */
	private boolean checkNum(String pNum){
		if( pNum == null)
			return false;
		pNum = pNum.trim();
		Pattern pattern = Pattern.compile("^(\\d+.\\d+)|(\\d+)$");
		Matcher m = pattern.matcher(pNum);
		if(StringUtils.isBlank(pNum)){
			return false;
		} else if(!m.matches()){
			return false;
		}
		return true;
	}

	/**
	 * 获得企业绑定的微博账号信息 GET_ENTERP_WEIBO
	 * 
	 * @param enterpWeiboCS
	 * @return
	 * @author 甘建新 2012-7-11下午11:53:27
	 */
	public byte[] getEnterpWeibo(byte[] bytes) {
		LOG_METHOD_NAME="getEnterpWeibo";
		
		PbEnterpWeiboSC.Builder pbEnterpWeiboSCB = PbEnterpWeiboSC.newBuilder();
		PbEnterpWeibo.Builder pbEnterpWeiboB = PbEnterpWeibo.newBuilder();
		if (bytes!=null) {
			try {
				PbEnterpWeiboCS pbEnterpWeiboCS = PbEnterpWeiboCS.parseFrom(bytes);
				int appId = pbEnterpWeiboCS.getIntAppId();
				
				log.info(LOG_METHOD_NAME+"【appId,"+appId+"】");
				
				UserWeiboTab weibo =userWeiboTabService.getEnterpWeibo(appId);
				if (weibo!=null) {
					pbEnterpWeiboB.setAPPKEY(weibo.getAppkey());
					pbEnterpWeiboB.setAPPSECRETKEY(weibo.getAppsecretkey());
					pbEnterpWeiboB.setCALLBACKURL(weibo.getCallbackurl());
					pbEnterpWeiboB.setIntAppId(weibo.getIntAppId());
					pbEnterpWeiboB.setIntWeiboId(weibo.getIntWeiboId());
					pbEnterpWeiboB.setIntWeiboType(weibo.getIntWeiboType());
					pbEnterpWeiboB.setVarWeiboName(weibo.getVarWeiboName());
					
					pbEnterpWeiboSCB.setPbEnterpWeibo(pbEnterpWeiboB);
					pbEnterpWeiboSCB.setExeResult(PBRESULT.SUCCESS);
					log.info(LOG_METHOD_NAME+Const.LOG_DATA_SUCCESS);
				}else {
					log.info(LOG_METHOD_NAME+Const.LOG_DATA_NULL);
					pbEnterpWeiboSCB.setExeResult(PBRESULT.NULL);
				}
			} catch (Exception e) {
				log.error(LOG_METHOD_NAME+Const.LOG_DATA_EXCEPTION,e);
				e.printStackTrace();
				pbEnterpWeiboSCB.setExeResult(PBRESULT.EXCEPTION);
			}
		}else {
			log.info(LOG_METHOD_NAME+Const.LOG_BYTE_NULL);
			pbEnterpWeiboSCB.setExeResult(PBRESULT.FAILED);
		}
		return pbEnterpWeiboSCB.build().toByteArray();
	}

	//Setter
	public void setEnterpShopTabService(EnterpShopTabService enterpShopTabService) {
		this.enterpShopTabService = enterpShopTabService;
	}

	public void setUserWeiboTabService(UserWeiboTabService userWeiboTabService) {
		this.userWeiboTabService = userWeiboTabService;
	}

	public void setTagValuesService(TagValuesService tagValuesService) {
		this.tagValuesService = tagValuesService;
	}

	public void setTagsService(TagsService tagsService) {
		this.tagsService = tagsService;
	}
}
